package com.example.superyi.mainBar.fregments;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import com.example.onion.hxchat.activity.AlterPassWordActivity;
import com.example.onion.hxchat.activity.AlterUserInfoActivity;
import com.example.onion.hxchat.activity.LoginActivity;
import com.example.onion.hxchat.activity.MainActivityWC;
import com.example.onion.hxchat.thread.GetUserNameThread;
import com.example.onion.hxchat.thread.PlayUserImg;
import com.example.onion.hxchat.util.ImgUtil;
import com.example.onion.hxchat.util.PassWordHelp;
import com.example.superyi.myteam.R;
import com.hyphenate.chat.EMClient;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Objects;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;

public class MainFragment_My extends Fragment {

    private static final int CHOOSE_PHOTO = 22;
    private static final int TAKE_PHOTOWC = 23;
    private Button logoutBtn;
    private View view;
    private Button alterPasswordBtn;
    private CircleImageView userImg;
    private TextView userName;
    private View mineLayout;
    private Uri imgUri;
    private String accountId;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.main_fragment_e, container, false);
        Log.v("test", "----------------运行到此处fragment_e_homepage");
        accountId = PassWordHelp.readPassword(requireContext())[0];
        new Thread(new PlayUserImg("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2534506313,1688529724&fm=26&gp=0.jpg",handler)).start();
        new Thread(new GetUserNameThread(accountId,handler)).start();
        initView();
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.v("test", "----------------运行到此处fragment的onViewcreated");

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PlayUserImg.PLAYIMG_IS_FAILED:
                    break;
                case PlayUserImg.PLAYIMG_IS_FINISH:
                    userImg.setImageIcon(Icon.createWithBitmap((Bitmap)msg.obj));
                    break;
                case GetUserNameThread.GETNAME_IS_FINISH:
                     userName.setText((String) msg.obj);
                    break;
                default:
                    break;
            }
        }
    };

    private void initView() {
        userName = view.findViewById(R.id.fragment_E_userName);
        logoutBtn = view.findViewById(R.id.fragment_E_logout_button);
        alterPasswordBtn = view.findViewById(R.id.fragment_E_alterPassword_button);
        userImg = view.findViewById(R.id.fragment_E_userImg);
        mineLayout = view.findViewById(R.id.fragment_E_mineLayout);//包括用户头像，昵称在内的那一行的布局，计划点击整个一行的布局的范围都可以查看我的具体信息（个人详细资料）
        logoutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
            }
        });
        alterPasswordBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(requireContext(), "跳转到改密码的页面", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(requireContext(), AlterPassWordActivity.class);
                startActivity(intent);
            }
        });
        userImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(requireContext(), "准备让你选择图片设置头像并处理上传图片的任务", Toast.LENGTH_SHORT).show();
                AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());

                builder.setIcon(R.drawable.ic_launcher_background);
                builder.setTitle("选择图片上传方式");
                //    指定下拉列表的显示数据
                final String[] cities = {"从相册中获取", "拍照"};
                //    设置一个下拉的列表选择项
                builder.setItems(cities, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(requireContext(), "选择的方式为：" + cities[which], Toast.LENGTH_SHORT).show();

                        if (cities[which].equals("从相册中获取")) {
                            if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(requireActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 11);
                            } else {
                                openAlbum();
                            }
//                            Intent picture = new Intent(
//                                    Intent.ACTION_PICK,
//                                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                            startActivityForResult(picture, 22);
                        } else if (cities[which].equals("拍照")) {//获取拍照权限
                            if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(requireActivity(), new String[]{Manifest.permission.CAMERA}, 12);
                            } else {
                                initTakePhoto();
                                // 启动相机程序
                                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
                                startActivityForResult(intent, TAKE_PHOTOWC);
                            }

                        }

                    }
                });
                builder.show();

            }
        });
        mineLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(requireContext(), "准备跳转查看个人详细信息", Toast.LENGTH_LONG).show();
                Intent intent = new Intent(requireContext(), AlterUserInfoActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 打开相册
     */
    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    /**
     * 调用拍照前的准备工作
     */
    private void initTakePhoto() {
        File file = new File(requireActivity().getExternalCacheDir(), "userImg.jpg");
        try {
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT < 24) {
            imgUri = Uri.fromFile(file);
        } else {
            imgUri = FileProvider.getUriForFile(requireContext(), "com.example.superyi.mainBar.fregments.MainFragment_My", file);
        }
    }

    /***
     *  处理运行时权限的请求和处理
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 11:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Toast.makeText(requireContext(), "您取消了授权", Toast.LENGTH_SHORT).show();
                }
                break;
            case 12:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                    startActivityForResult(intent,TAKE_PHOTOWC);
                    initTakePhoto();
                    // 启动相机程序
                    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
                    startActivityForResult(intent, TAKE_PHOTOWC);
                } else {
                    Toast.makeText(requireContext(), "您取消了授权", Toast.LENGTH_SHORT).show();
                }
                break;

            default:
                break;
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    assert data != null;
                    String filePath = handleImageOnKitKat(data);
                    //上传
                    Log.d("tag filepath", filePath);

                }
                break;
            case TAKE_PHOTOWC:
                if (resultCode == RESULT_CANCELED) {
                    Toast.makeText(requireContext(), "取消了拍照", Toast.LENGTH_LONG).show();
                    break;
                }
                try {
                    // 将拍摄的照片显示出来
                    Bitmap bitmap = BitmapFactory.decodeStream(requireContext().getContentResolver().openInputStream(imgUri));
                    File file = new File(String.valueOf(imgUri));
//                    String path = ImgUtil.getRealFilePath(requireContext(),imgUri);
//                    Log.e("拍摄图片路径",path);
                    userImg.setImageBitmap(bitmap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }


//    /**
//     * 上传到接口
//     * retrofit
//     *
//     * @param picPath
//     * @param file
//     * @Post Observable<ResponseBody> onepic(@Url String url, @Header("sessionId") String sessionId, @Header("userId") String userId, @Part MultipartBody.Part file);
//     */
//    private void addimg(String picPath, File file) {
//        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            Log.e("123", "图片文件路径: " + picPath);
//            //创建文件请求对象
//            //设置content-type类型
//            RequestBody responseBody = RequestBody.create(MediaType.parse("image/*"), file);//file为文件
//            //多表单上传的工具类
//            MultipartBody.Part image = MultipartBody.Part.createFormData("image", picPath, responseBody);
////            HttpUntil.getUntil().getService(UserApiService.class).onepic(url, sessionId, userId, image)
////                    .subscribeOn(Schedulers.io())
////                    .observeOn(AndroidSchedulers.mainThread())
////                    .subscribe(new Consumer<ResponseBody>() {
////                        @Override
////                        public void accept(ResponseBody responseBody) throws Exception {
////                            Log.e("123", "上传图片成功: " + responseBody.string());
////                        }
////                    }, new Consumer<Throwable>() {
////                        @Override
////                        public void accept(Throwable throwable) throws Exception {
////                            Log.e("123", "上传图片失败-: " + throwable);
////                        }
////                    });
//        }
//    }








    /**
     * 处理图片，主要是怎么获得图片的真实地址（抄的）
     * 顺便返回文件地址用于上传图片
     *
     * @param data
     */
    private String handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        Log.d("TAG", "handleImageOnKitKat: uri is " + uri);
        if (DocumentsContract.isDocumentUri(requireContext(), uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            assert uri != null;
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1]; // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.parseLong(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        displayImage(imagePath); // 根据图片路径显示图片
        return imagePath;
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = requireContext().getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            userImg.setImageBitmap(bitmap);
        } else {
            Toast.makeText(requireContext(), "failed to get image", Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 集成环信退出登录 EMClient.getInstance().logout(true)；
     * 顺便实现删除保存的登录的用户的账号，完成LoginActivity类说明的功能
     */
    private void logout() {
        //将空值的用户账户和密码保存，覆盖先前的数据实现清除账户数据，
//        PassWordHelp.savePassword(requireActivity(), "", "", false);
//        String accountId = PassWordHelp.readPassword(requireActivity())[0];
//        String pwd = PassWordHelp.readPassword(requireActivity())[1];
//        Log.e("MainActivityWC", "保存null之后获取的accountId" + accountId);
//        Log.e("MainActivityWC", "保存null之后获取的pwd" + pwd);
        // 以便可以通过PassWordHelp能否获取数据判断用户登录状态
        EMClient.getInstance().logout(true);
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
        Toast.makeText(getActivity(), "退出登录", Toast.LENGTH_SHORT).show();
    }

}